package question;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

/**
 * 问题6：多线程统计并求最大值
 *
 * @author 阳秋豪
 * @createTime 2024/3/12
 */
public class Test6 {
    /*在上一题基础上继续完成如下需求:
      每次抽的过程中，不打印，抽完时一次性打印(随机)
      在此次抽奖过程中，抽奖箱1总共产生了6个奖项
          分别为:10,20,100,500,2,300最高奖项为300元，总计额为932元
      在此次抽奖过程中，抽奖箱2总共产生了6个奖项
          分别为:5,50,200,800,80,700最高奖项为800元，总计额为1835元
    */
    public static void main(String[] args) throws InterruptedException {
        ArrayList<Integer> arrayList = new ArrayList<>();
        Collections.addAll(arrayList, 10, 5, 20, 50, 100, 200, 500, 800, 2, 80, 300, 700);
        QRunnable6 runnable = new QRunnable6(arrayList);
        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);
        t1.setName("抽奖箱1");
        t2.setName("抽奖箱2");
        t1.start();
        t2.start();
    }
}

class QRunnable6 implements Runnable {
    ArrayList<Integer> arrayList;
    Random random = new Random();

    public QRunnable6(ArrayList<Integer> arrayList) {
        this.arrayList = arrayList;
    }

    @Override
    public void run() {
        ArrayList<Integer> list = new ArrayList<>();
        while (true) {
            synchronized (QRunnable6.class) {
                if (arrayList.isEmpty()) {
                    sout(list, Thread.currentThread().getName());
                    break;
                } else {
                    int i = random.nextInt(arrayList.size());
                    Integer remove = arrayList.remove(i);
                    list.add(remove);
                }
            }
            // 更好的看出来线程的交替
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 输出中奖号码
     *
     * @param list 抽奖箱
     * @param name 调用线程名
     */
    private void sout(ArrayList<Integer> list, String name) {
        System.out.println("在此次抽奖过程中，" + name + "总共产生了" + list.size() + "个奖项");
        System.out.println("\t分别为" + list);
        System.out.println("\t最大奖项是" + Collections.max(list));
        int sum = 0;
        for (Integer i : list) {
            sum += i;
        }
        System.out.println("\t总计额为" + sum + "元");
    }
}